<?php

// -----------------------------------------------------------------------------

include "config/config.php";
include "DBManager.php";
include "global/functions.php";
include "createDBIfNotExists.php";

// 取消超时
set_time_limit(0);

$db = new DBManager($dbPath);

// -----------------------------------------------------------------------------

if (empty($_POST['startDate']) || empty($_POST['contents']) || empty($_POST['dailyVolume']) || empty($_POST['order'])) {
    exit("需要传入有效的参数。");
}

$startDate = $_POST['startDate'];
$contents = $_POST['contents'];
$dailyVolume = $_POST['dailyVolume'];
$order = $_POST['order'];

// -----------------------------------------------------------------------------

$arr = explode(PHP_EOL, $contents);

if ($order == "random") {
    shuffle($arr); // 数组乱序
}

$wordsArr = [];
// 去除数组中数值为空的元素
foreach ($arr as $item) {
    if (!empty($item)) {
        $wordsArr[] = $item;
    }
}

// -----------------------------------------------------------------------------
?>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>批量制定复习计划</title>
    <link rel="stylesheet" href="resources/bootstrap-4.3.1-dist/css/bootstrap.min.css">
</head>
<body>

<!-- ----------------------------------------------------------------------- -->

<?php include 'global/globalNavBar.php'; ?>

<!-- ----------------------------------------------------------------------- -->

<div class="container mt-2">

    <?php

    try {

        $dateToAppend = $startDate;
        $contentsToInsert = "";
        $counter = 1;

        foreach ($wordsArr as $item) {

            // 每遍历一次，就将新的 item 添加到 $contentsToinsert 中
            $contentsToInsert .= $item . PHP_EOL;

            if (($counter % $dailyVolume) == 0) {
                $db->appendContent($dateToAppend, $contentsToInsert);
                $dateToAppend = getTheDate($dateToAppend, "+", 1);
                $contentsToInsert = "";
            } else {
                if ($counter == count($wordsArr)) {
                    $db->appendContent($dateToAppend, $contentsToInsert);
                }
            }

            $counter += 1;

        }

        echo "数据插入成功。";

    } catch (Exception $e) {
        echo $e->getMessage();
    }

    ?>

</div>

<!-- ----------------------------------------------------------------------- -->

<script src="resources/jquery/jquery-3.4.0.min.js"></script>
<script src="resources/bootstrap-4.3.1-dist/js/bootstrap.min.js"></script>

<!-- ----------------------------------------------------------------------- -->

</body>
</html>
